/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spwpanel;

import context.Client;
import hibernate.data.ProjectKinds;
import hibernate.data.Projects;
import hibernate.data.Users;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Norteromius
 */
public class ProjectWindow extends javax.swing.JFrame {
    
    
    Client client = null;
    
    Projects mainProj = null;
    

    /**
     * Creates new form ProjectWindow
     */
    public ProjectWindow(Client client) {
        initComponents();
        
        
        this.client = client;
        
        
        List usersList = client.getSession().createCriteria(Users.class).list();
        
        ArrayList managerList = new ArrayList();
        if(usersList != null && usersList.size() > 0){
            for (int i =0; i < usersList.size(); i++){
                Users user = (Users) usersList.get(i);
                if (user.getUrsKind().getUksName().equalsIgnoreCase(
                    "Project Manager")){
                    managerList.add(user);
                }
            }
        }
        
        
        
        
        for (int i = 0; i < managerList.size(); i++){
            Users manager = (Users)managerList.get(i);
            this.managerBox.addItem(manager.getUrsLastName() + " " + manager.getUrsFirstName());
        }
        
        
        List kindsList = client.getSession().createCriteria(ProjectKinds.class).list();
        
        for (int i=0; i< kindsList.size(); i++){
            ProjectKinds projKind = (ProjectKinds)kindsList.get(i);
            this.kindBox.addItem(projKind.getPjkKind());
        }
        
        
    }
    
    public ProjectWindow(Client client, Projects project) {
        initComponents();
        
        this.mainProj = project;
        this.client = client;
        
        
        List usersList = client.getSession().createCriteria(Users.class).list();
        
        ArrayList managerList = new ArrayList();
        if(usersList != null && usersList.size() > 0){
            for (int i =0; i < usersList.size(); i++){
                Users user = (Users) usersList.get(i);
                if (user.getUrsKind().getUksName().equalsIgnoreCase(
                    "Project Manager")){
                    managerList.add(user);
                }
            }
        }
        
        
        
        
        for (int i = 0; i < managerList.size(); i++){
            Users manager = (Users)managerList.get(i);
            this.managerBox.addItem(manager.getUrsLastName() + " " + manager.getUrsFirstName());
            if(manager.getUrsId() == project.getPrjManager().getUrsId()){
                this.managerBox.setSelectedIndex(i);
            }
        }
        
        
        List kindsList = client.getSession().createCriteria(ProjectKinds.class).list();
        
        for (int i=0; i< kindsList.size(); i++){
            ProjectKinds projKind = (ProjectKinds)kindsList.get(i);
            this.kindBox.addItem(projKind.getPjkKind());
            if(projKind.getPjkId() == project.getPrjKind().getPjkId()){
                this.kindBox.setSelectedIndex(i);
            }
        }
        
        
        this.nameField.setText(project.getPrjName());
        
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        kindBox = new javax.swing.JComboBox();
        managerBox = new javax.swing.JComboBox();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        errorLable = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Nazwa:");

        jLabel2.setText("Rodzaj:");

        jLabel3.setText("Kierownik Projektu:");

        okButton.setText("Utwórz");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Anuluj");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        errorLable.setForeground(new java.awt.Color(204, 0, 51));
        errorLable.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(nameField)
                        .addComponent(kindBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(managerBox, 0, 212, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(okButton)
                        .addGap(18, 18, 18)
                        .addComponent(cancelButton)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(errorLable, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(103, 103, 103))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(kindBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(managerBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(56, 56, 56)
                .addComponent(errorLable)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap(32, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        // TODO add your handling code here:
        clearErrors();
        String name = nameField.getText();
        if (name == null || name.isEmpty()){
            nameField.setBackground(Color.red);
            errorLable.setText("Podaj nazwę projektu!");
            return;
        }
        
        
        
        Session ses = client.getSession();
        
         List proj = ses.createCriteria(Projects.class).add(Restrictions.eq("prjName", name)).list();
        if (proj != null && proj.size()>0){
            nameField.setBackground(Color.red);
            errorLable.setText("Istnieje projekt o podanej nazwie!");
            return;
            
        }
        
        
        
        List managers = ses.createCriteria(Users.class).list();
        Users manager = null;
        for (int i = 0; i < managers.size(); i++){
            Users user = (Users) managers.get(i);
            if (user.getUrsKind().getUksName().equalsIgnoreCase("Project Manager") &&
                    (user.getUrsLastName() + " " + user.getUrsFirstName()).equalsIgnoreCase((String)managerBox.getSelectedItem())){
                manager = user;
                break;
                
            }
        }
        
        String kind = (String) kindBox.getSelectedItem();
        List <ProjectKinds> kinds =ses.createCriteria(ProjectKinds.class).add(Restrictions.eq("pjkKind", kind)).list();
        
        if (mainProj != null){
            mainProj.setPrjName(name);
            mainProj.setPrjManager(manager);
            mainProj.setPrjKind(kinds.get(0));
           ses.update(mainProj);
           setVisible(false);
           return;
        }
        
        Projects newProj = new Projects(new Date(), null, kinds.get(0), name, manager);
        
        ses.save(newProj);
        
        setVisible(false);
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void clearErrors (){
            nameField.setBackground(Color.white);

            errorLable.setText("");
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProjectWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProjectWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProjectWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProjectWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //new ProjectWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel errorLable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JComboBox kindBox;
    private javax.swing.JComboBox managerBox;
    private javax.swing.JTextField nameField;
    private javax.swing.JButton okButton;
    // End of variables declaration//GEN-END:variables
}
